import global from './global'
const upload = (formData) => {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      success: (chooseImageRes) => {
        const tempFilePaths = chooseImageRes.tempFilePaths;
		//uni.showLoading({title:"上传图片中"});
        uni.uploadFile({
          url: global.host + '/upload',
          // url: 'https://oa-info-test.infinitus-int.com/v1/uploadFile',
          filePath: tempFilePaths[0],
          name: 'file',
          formData,
          success: (uploadFileRes) => {
            console.log(JSON.parse(uploadFileRes.data));
            resolve(JSON.parse(uploadFileRes.data))
          },
          fail: error => {
		    //uni.hideLoading();
            reject(error);
          },
		  complete:()=>{
			//uni.hideLoading();
		  }
        });
      }
    });
  })
}

const getBase64 = url => {
  return new Promise((resolve, reject) => {
    var Img = new Image()
    var dataURL = ''
    Img.setAttribute('crossOrigin', 'Anonymous')
    Img.crossOrigin = '';
    Img.src = url + '?v=' + Math.random()
    Img.onload = function () {
      // 要先确保图片完整获取到，这是个异步事件
      var canvas = document.createElement('canvas') // 创建canvas元素
      var width = Img.width // 确保canvas的尺寸和图片一样
      var height = Img.height
      canvas.width = width
      canvas.height = height
      canvas.getContext('2d').drawImage(Img, 0, 0, width, height) // 将图片绘制到canvas中
      dataURL = canvas.toDataURL('image/jpeg') // 转换图片为dataURL
      resolve(dataURL)
    }
  })
}
const postApi = async (url, data = {}) => {
  try {
    let res =await uni.request({
      url: global.host + url,
      timeout: 6000,
      data,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      }
    })
	return res[1].data
  } catch (error) {
    Promise.reject(error)
  }
}

const getApi = async (url, data = {}) => {
  try {
    let res = await uni.request({
      url: global.host + url,
      timeout: 15000,
      data,
      method: 'GET',
      header: {
        'content-type': 'application/json;charset=UTF-8'
      }
    })
	
    return res[1].data
  } catch (error) {
    Promise.reject(error)
	return null;
  }
}
module.exports = {
  upload,
  getBase64,
  postApi,
  getApi
}